﻿﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using System.Threading.Tasks;
 using System.Xml.Serialization;

namespace Xbb.Common.Helpers
{
    public static class XmlHelper
    {

        /// <summary>  
        /// 反序列化  
        /// </summary>  
        /// <param name="type">类型</param>  
        /// <param name="xml">XML字符串</param>  
        /// <returns></returns>  
        public static object Deserialize(Type type, string xml)
        {
            using (StringReader sr = new StringReader(xml))
            {
                XmlSerializer xmldes = new XmlSerializer(type);
                return xmldes.Deserialize(sr);
            }
        }
        /// <summary>  
        /// 反序列化  
        /// </summary>  
        /// <param name="type"></param>  
        /// <param name="xml"></param>  
        /// <returns></returns>  
        public static object Deserialize(Type type, Stream stream)
        {
            XmlSerializer xmldes = new XmlSerializer(type);
            return xmldes.Deserialize(stream);
        }
        public static T GetObjectFromXml<T>(this string xml)
        {
            if (string.IsNullOrEmpty(xml))
            {
                return default(T);
            }
            else
            {
                DataContractSerializer serializer = new DataContractSerializer(typeof(T));
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(xml)))
                {
                    return (T)serializer.ReadObject(stream);
                }
            }
        }

        public static string ObjectToXml(this Object obj)
        {
            using (MemoryStream memStm = new MemoryStream())
            {
                var serializer = new DataContractSerializer(obj.GetType());
                serializer.WriteObject(memStm, obj);

                memStm.Seek(0, SeekOrigin.Begin);

                using (var streamReader = new StreamReader(memStm))
                {
                    string result = streamReader.ReadToEnd();
                    return result;
                }
            }

        }
    }
}